//
//  HPCache.m
//  HPNetworking
//
//  Created by phq on 2019/9/26.
//  Copyright © 2019 pixy. All rights reserved.
//

#import "HPCache.h"
#import "HPRequestModel.h"
#import "HPHelper.h"
#import "HPRequest.h"

@implementation HPCache

#pragma mark - public

// save cache
- (BOOL)cacheData:(NSDictionary *)data userId:(NSString *)uid model:(HPRequestModel *)model {
    if (!data || ![data isKindOfClass:[NSDictionary class]]) {return NO;};
    NSString *filePath = [self getFilePathWithUserId:uid model:model];
    NSString *value = [HPHelper base64EncodedWithString:[HPHelper stringWithJson:data]];
    return [value writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

// get cache
- (NSDictionary *)getCacheWithUserId:(NSString *)uid model:(HPRequestModel *)model {
    NSString *filePath = [self getFilePathWithUserId:uid model:model];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSString *value = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [HPHelper dataWithBase64EncodedString:value];
        NSString *result =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *info = [HPHelper dictionaryWithJsonString:result];
        return info;
    }
    return nil;
}

// remove a cache
- (BOOL)removeCacheUserId:(NSString *)uid model:(HPRequestModel *)model  {
    NSString *filePath = [self getFilePathWithUserId:uid model:model];
    return [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}

// remove all cache
- (BOOL)removeAllRequestCache {
    return YES;
//    NSString *path = [self getCacheFolderPath];
//    NSFileManager *fm = [NSFileManager defaultManager];
//    return [fm removeItemAtPath:path error:nil];
}

#pragma mark - internal

- (NSString *)getFilePathWithUserId:(NSString *)uid model:(HPRequestModel *)model {
    HPInfo *info = [HPNetworking infoOnType:model.type];
    NSString *key = [NSString stringWithFormat:@"cache_%@_%@_%@",uid,info.url,model.postParams];
    return [self cacheFilePathWithTag:[HPHelper md5WithString:key]];
}

// get cache path
- (NSString *)cacheFilePathWithTag:(NSString *)tag {
    NSString *path = [self getCacheFolderPath];
    NSString *name = [NSString stringWithFormat:@"%@.plist",tag];
    return [path stringByAppendingPathComponent:name];
}

// get the cache folder path
- (NSString *)getCacheFolderPath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = paths.firstObject;
    NSString *documentPath = [cachePath stringByAppendingPathComponent:@"AppRequestCache"];
    return documentPath;
    
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
//    NSString *cachePath = paths.firstObject;
//    NSString *documentPath = [cachePath stringByAppendingPathComponent:@"AppRequestCache"];
//    NSLog(@"\n\n-----创建缓存文件夹路径--documentPath=%@--\n\n",documentPath);
//    BOOL isDir;
//    NSFileManager *fm = [NSFileManager defaultManager];
//    if([fm fileExistsAtPath:documentPath isDirectory:&isDir] && isDir) {
//        return documentPath;
//    }else if ([fm createDirectoryAtPath:documentPath withIntermediateDirectories:YES attributes:nil error:nil]) {
//        return documentPath;
//    }else {
//        NSLog(@"\n\n-----创建缓存文件夹出错----\n\n");
//        return nil;
//    }
}

@end


static NSString *KeyDirectory = @"YwRecode";
@implementation HPCache (Recode)

// save
- (BOOL)saveData:(NSDictionary *)data userId:(NSString *)uid funcTag:(NSString *)funcTag {
    if (!data || ![data isKindOfClass:[NSDictionary class]]) {return NO;};
    NSString *filePath = [self filePathWithUserId:uid funcTag:funcTag];
    NSString *value = [HPHelper base64EncodedWithString:[HPHelper stringWithJson:data]];
    return [value writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

// get
- (NSDictionary *)getDataWithUserId:(NSString *)uid funcTag:(NSString *)funcTag {
    NSString *filePath = [self filePathWithUserId:uid funcTag:funcTag];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSString *value = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [HPHelper dataWithBase64EncodedString:value];
        NSString *result =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *info = [HPHelper dictionaryWithJsonString:result];
        return info;
    }
    return nil;
}

// remove
- (BOOL)removeWithUserId:(NSString *)uid funcTag:(NSString *)funcTag  {
    return YES;
//    NSString *filePath = [self filePathWithUserId:uid funcTag:funcTag];
//    return [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}

// remove all
- (BOOL)removeAll {
    return YES;
//    NSString *path = [self libraryFolderPath];
//    NSFileManager *fm = [NSFileManager defaultManager];
//    return [fm removeItemAtPath:path error:nil];
}

#pragma mark - internal

- (NSString *)filePathWithUserId:(NSString *)uid funcTag:(NSString *)funcTag {
    NSString *tag = [NSString stringWithFormat:@"Record_%@_%@",uid,funcTag];
    return [self filePathWithTag:tag];
}

// get Library path
- (NSString *)filePathWithTag:(NSString *)tag {
    NSString *path = [self libraryFolderPath];
    NSString *name = [NSString stringWithFormat:@"%@.plist",tag];
    return [path stringByAppendingPathComponent:name];
}

// get the Library folder path
- (NSString *)libraryFolderPath {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *cachePath = paths.firstObject;
    NSString *documentPath = [cachePath stringByAppendingPathComponent:KeyDirectory];
    return documentPath;
    
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
//    NSString *cachePath = paths.firstObject;
//    NSString *documentPath = [cachePath stringByAppendingPathComponent:KeyDirectory];
//    NSLog(@"\n\n-----创建缓存文件夹路径--documentPath=%@--\n\n",documentPath);
//    BOOL isDir;
//    NSFileManager *fm = [NSFileManager defaultManager];
//    if([fm fileExistsAtPath:documentPath isDirectory:&isDir] && isDir) {
//        return documentPath;
//    }else if ([fm createDirectoryAtPath:documentPath withIntermediateDirectories:YES attributes:nil error:nil]) {
//        return documentPath;
//    }else {
//        NSLog(@"\n\n-----创建缓存文件夹出错----\n\n");
//        return nil;
//    }
}


@end
